package com.ellen.mac.chatdemo.handler;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.avos.avoscloud.AVCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMConversation;
import com.avos.avoscloud.im.v2.AVIMTypedMessage;
import com.avos.avoscloud.im.v2.AVIMTypedMessageHandler;
import com.avos.avoscloud.im.v2.messages.AVIMTextMessage;
import com.ellen.mac.chatdemo.R;
import com.ellen.mac.chatdemo.cache.ConversationItemCache;
import com.ellen.mac.chatdemo.cache.ProfileCache;
import com.ellen.mac.chatdemo.comment.BaseApp;
import com.ellen.mac.chatdemo.event.TypeMessageEvent;
import com.ellen.mac.chatdemo.model.ChatKitUser;
import com.ellen.mac.chatdemo.utils.ChatKit;
import com.ellen.mac.chatdemo.utils.LogUtils;
import com.ellen.mac.chatdemo.utils.NotificationUtils;

import org.greenrobot.eventbus.EventBus;


/**
 * Created by mac on 2017/11/29.
 */

public class CustomMessageHandler extends AVIMTypedMessageHandler<AVIMTypedMessage> {
    //接收到消息后的处理逻辑
    private Context context;

    public CustomMessageHandler(Context context) {
        this.context = context.getApplicationContext();
    }

    @Override
    public void onMessage(AVIMTypedMessage message, AVIMConversation conversation, AVIMClient client) {
        Log.i("tag", "----message.getMessageType()----" + message.getMessageType());
        if (message == null || message.getMessageId() == null) {
            LogUtils.d( "may be SDK Bug, message or message id is null");
            return;
        }
        if (ChatKit.getInstance().getCurrentUserId() == null) {
            LogUtils.d( "selfId is null, please call LCChatKit.open!");
            client.close(null);
        } else {
            if (!client.getClientId().equals(ChatKit.getInstance().getCurrentUserId())) {
                client.close(null);
            } else {
                if (NotificationUtils.isShowNotification(conversation.getConversationId())) {
                    sendNotification(message, conversation);
                }
                ConversationItemCache.getInstance().insertConversation(message.getConversationId());
                if (!message.getFrom().equals(client.getClientId())) {
                    sendEvent(message, conversation);
                }
            }
        }
    }

    @Override
    public void onMessageReceipt(AVIMTypedMessage message, AVIMConversation conversation, AVIMClient client) {
        super.onMessageReceipt(message, conversation, client);
    }

    /**
     * 发送消息到来的通知事件
     *
     * @param message
     * @param conversation
     */
    private void sendEvent(AVIMTypedMessage message, AVIMConversation conversation) {
        TypeMessageEvent event = new TypeMessageEvent();
        event.message = message;
        event.conversation = conversation;
        EventBus.getDefault().post(event);
    }

    private void sendNotification(final AVIMTypedMessage message, final AVIMConversation conversation) {
        if (null != conversation && null != message) {
            final String notificationContent = message instanceof AVIMTextMessage ?
                    ((AVIMTextMessage) message).getText() : context.getString(R.string.unspport_message_type);
            ProfileCache.getInstance().getCachedUser(message.getFrom(), new AVCallback<ChatKitUser>() {
                @Override
                protected void internalDone0(ChatKitUser userProfile, AVException e) {
                    if (e != null) {
                        LogUtils.logException(e);
                    } else if (null != userProfile) {
                        String title = userProfile.getName();
                        Intent intent = getIMNotificationIntent(conversation.getConversationId(), message.getFrom());
                        NotificationUtils.showNotification(context, title, notificationContent, null, intent);
                    }
                }
            });
        }
    }

    /**
     * 点击 notification 触发的 Intent
     * 注意要设置 package 已经 Category，避免多 app 同时引用 lib 造成消息干扰
     *
     * @param conversationId
     * @param peerId
     * @return
     */
    private Intent getIMNotificationIntent(String conversationId, String peerId) {
        Intent intent = new Intent();
        intent.setAction(BaseApp.CHAT_NOTIFICATION_ACTION);
        intent.putExtra(BaseApp.CONVERSATION_ID, conversationId);
        intent.putExtra(BaseApp.PEER_ID, peerId);
        intent.setPackage(context.getPackageName());
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        return intent;
    }
}